<template>
  <div class="handwritten-name-wrap">
    <div v-if="!ifWrite">
      <el-form :model="currentRecord" ref="Signature" :rules="recordRules" label-width="120px">
        <el-form-item label="签名:" prop="imgSrc">
          <el-col :span="18">
            <el-button @click="handleWrite" type="primary" v-if="!imgSrc">点击签名</el-button>
            <div style="width: 100%;border: 1px solid;position: relative;" v-else>
              <img :src="imgSrc" style="width: 100%;">
              <i class="el-icon-circle-close" @click="imgSrc = null"
                style=" position: absolute; right:0px; top:0px;font-size: 30px;color: red;"></i>
            </div>
            </img>
          </el-col>
        </el-form-item>
        <el-form-item label="选择分发人员:" prop="receiverIds" v-if="!roles.includes('direct_seller')">
          <el-col :span="18">
            <el-cascader v-model="currentRecord.receiverIds" style="width: 100%;" :options="optionsList" :props="props"
              :show-all-levels="false">
              <template #default="{ node, data }"> <!-- 注意使用的是 #default -->
                <span>{{ data.name }}{{ data.roleName ? `&nbsp&nbsp(${data.roleName})` : '' }}</span>
                <!-- 假设每个选项对象中有一个otherField字段 -->
              </template>
            </el-cascader>
          </el-col>
        </el-form-item>
        <el-form-item align="center">
          <el-col :span="24">
            <el-button type="primary" @click.native.prevent="handleSubmit">
              <i class="fa fa-save"></i> 分发
            </el-button>
          </el-col>
        </el-form-item>
      </el-form>
    </div>
    <div v-else>
      <div style="border: 1px solid #000;">
        <VueSignaturePad width="100%" height="300px" ref="signaturePad" :options="options" />
      </div>

      <footer style="margin-top: 10px;">
        <div class="gtnGroup">
          <el-button type="primary" size="mini" @click="undo">撤销</el-button>
          <el-button type="primary" size="mini" style="margin-left:20px" @click="clear">清屏</el-button>
          <el-button type="primary" size="mini" style="margin-left:20px" @click="save">确认</el-button>
        </div>
        <div class="otherSet">
          <div class="penTxt">笔刷大小：</div>
          <div class="circleWrap" :class="{ active: isActive1 }" @click="selSize(1)"><b class="b1"></b></div>
          <div class="circleWrap" :class="{ active: isActive2 }" @click="selSize(2)"><b class="b2"></b></div>
          <div class="circleWrap" :class="{ active: isActive3 }" @click="selSize(3)"><b class="b3"></b></div>
        </div>
      </footer>
    </div>
  </div>
</template>
<script>
import DistributionApi from '../api/distribution'
import { Message, Loading } from 'element-ui'
import {URL,minioUrl} from '@/api/api'
import { getToken } from '@/utils/auth'
import axios from "axios"
import { warn } from '@vue/composition-api'
export default {
  props: {
    record: {
      type: Object
    },
  },
  data() {
    const validateLogo = (rule, value, callback) => {

      if (!this.imgSrc) {

        callback(new Error('请签名'))
      } else {
        callback()
      }
    }
    return {
      panelVisible: false,
      panelTitle: "",
      currentRecord: {},
      recordRules: {},
      optionsList: [],
      props: { multiple: true, value: 'id', label: 'name' },
      options: {
        penColor: "#000",
        minWidth: 1,    //控制画笔最小宽度
        maxWidth: 1,    //控制画笔最大宽度
        backgroundColor: "rgba(255, 255, 255)",
      },
      recordRules: {
        receiverIds: [{ required: true, trigger: 'blur', message: '请输入分发人员' }],
        imgSrc: [{ required: true, validator: validateLogo, trigger: 'change' }],
      },
      isActive1: true,
      isActive2: false,
      isActive3: false,
      imgSrc: undefined,
      ifWrite: false,
      roles: []
    }
  },
  mounted() {
    this.imgSrc = undefined
    this.roles = this.$store.getters.roles
    DistributionApi.getPeerAndSubDeptsWithUsers().then(res => {
      this.optionsList = [...res.data.data.peerDepartments, ...res.data.data.subDepartments]
    })
  },
  methods: {

    handleSubmit() {
      this.$refs['Signature'].validate(async valid => {
        if (valid) {
          this.currentRecord.mainRecordId = this.record.distributionId
          let fileData = await this.uploadFile(this.base64ToFile(this.imgSrc, "qianming.png"))

          let writeData = await DistributionApi.receiveFile({ distributionId: this.record.distributionId, nodeId: this.record.relationId, fileId: fileData.fileId })
          if (this.roles.includes('direct_seller') && writeData.data.code == 200) {
            Message.success('签名成功')
            this.editLoading = false
            this.$emit('after-signature')
          }
          if (writeData.data.code == 200) {
            this.currentRecord.receiverIds = this.currentRecord.receiverIds.map(item => item[1])
            let newRecord = Object.assign({}, this.currentRecord)
            this.editLoading = true
            DistributionApi.add(newRecord).then(rspData => {
              if (rspData.data.code === 200) {
                Message.success('分发成功')
              } else {
                Message.error(rspData.data.message)
              }
              this.editLoading = false
              this.$emit('after-signature')
            })
          } else {
            this.imgSrc = undefined
            this.editLoading = false
            this.$emit('after-signature')
            return Message.error(writeData.data.message)
          }
        }

      })
    },
    handleWrite() {
      this.ifWrite = true
    },
    //手写签名按钮的点击
    handleClick() {
      this.panelVisible = true;
      this.isActive1 = true;
      this.isActive2 = false;
      this.isActive3 = false;
      this.options = {
        penColor: "#000",
        minWidth: 1,
        maxWidth: 1,
      }
    },
    //撤销
    undo() {
      this.$refs.signaturePad.undoSignature();
    },
    //清除
    clear() {
      this.$refs.signaturePad.clearSignature();
    },
    async uploadFile(files) {
      return new Promise(async (resolve, reject) => {
        const formData = new FormData();
        formData.append('file', files); //
        try {
          const response = await axios.post(URL + "/file/upload", formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              "Authorization": getToken()
            }
          });
          resolve(response.data.data)
        } catch (error) {
          Message.error('文件上传失败');
        }
      })

    },
    //保存
    async save() {

      const { isEmpty, data } = this.$refs.signaturePad.saveSignature();
      // let secureWrite = await this.changImg(data)
      this.imgSrc = data
      this.ifWrite = false
      this.$nextTick(() => {
        this.$refs['Signature'].clearValidate(["files"]);
      })
    },
    //调节画笔粗细大小
    selSize(val) {
      this.options = {
        penColor: "#000",
        minWidth: val,
        maxWidth: val,
      };
      if (val == 1) {
        this.isActive1 = true;
        this.isActive2 = false;
        this.isActive3 = false;
      } else if (val == 2) {
        this.isActive1 = false;
        this.isActive2 = true;
        this.isActive3 = false;
      } else if (val == 3) {
        this.isActive1 = false;
        this.isActive2 = false;
        this.isActive3 = true;
      }
    },
    changImg(base64Image) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = base64Image;
        img.onload = function () {
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');

          // // // 旋转 90 度，交换宽高
          // canvas.width = img.height;
          // canvas.height = img.width;

          // // 移动原点到左下角
          // ctx.translate(0, canvas.height);
          // // 逆时针旋转 90 度，使用负角度
          // ctx.rotate(-Math.PI / 2);

          // 绘制图片
          ctx.drawImage(img, 0, 0);

          // 获取旋转后的 Base64 数据
          const rotatedBase64 = canvas.toDataURL('image/png');
          resolve(rotatedBase64)
        }
      })

    },
    base64ToFile(base64Str, fileName) {
      var arr = base64Str.split(',')
      var mime = arr[0].match(/:(.*?);/)[1] // base64解析出来的图片类型
      // 对base64串进行操作，去掉url头，并转换为byte   atob为window内置方法
      var bstr = atob(arr[1])
      var len = bstr.length
      var ab = new ArrayBuffer(len) // 将ASCII码小于0的转换为大于0
      var u8arr = new Uint8Array(ab) //
      while (len--) {
        u8arr[len] = bstr.charCodeAt(len)
      };
      // 创建新的 File 对象实例[utf-8内容，文件名称或者路径，[可选参数，type：文件中的内容mime类型]]
      return new File([u8arr], fileName, {
        type: mime
      })
    }
  },
}
</script>
<style lang="scss">
.el-cascader-panel {
  height: 400px !important;
  overflow-y: auto !important;
}
.handwritten-name-wrap {
  .img-wrap {
    width: 100%;
    height: 164px;
    margin-top: 2px;
    border: 1px solid #ccc;

    img {
      width: 70%;
      height: 100%;
    }
  }


  footer {
    height: 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .gtnGroup {
      width: 50%;
      margin-left: 20px;
    }

    .otherSet {
      width: 50%;
      display: flex;
      align-items: center;

      .penTxt {
        width: 70px;
      }

      .selSize {
        width: 70px;
      }

      .el-select__caret {
        position: absolute;
        right: -3px;
      }

      .b1,
      .b2,
      .b3 {
        display: inline-block;
        background: #000;
        border-radius: 50%;
      }

      .circleWrap {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 18px;
        height: 18px;
        cursor: pointer;
        margin-right: 20px;
      }

      .active {
        border: 1px dashed #0074d9;
      }

      .b1 {
        width: 4px;
        height: 4px
      }

      .b2 {
        width: 6px;
        height: 6px
      }

      .b3 {
        width: 8px;
        height: 8px
      }
    }
  }
}


.signNameModel {
  .vxe-modal--content {
    padding: 0 !important;
  }
}
</style>